package com.gljx.web.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gljx.util.CommonExport;
import com.gljx.util.stateToString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gljx.util.GetFid;
import com.gljx.util.TimeFormat;
import com.gljx.web.Entity.Car;
import com.gljx.web.Entity.Department;
import com.gljx.web.Entity.PageBean;
import com.gljx.web.Entity.User;
import com.gljx.web.service.CarService;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;


@Controller
@RequestMapping("/")
public class CarController {

	//自动注入
	@Autowired
	private CarService carService;

	//自动注入
	@Autowired
	private DepartmentService departmentService;

	//自动注入
	@Autowired
	private CustomLogService customLogService;

	/**
	 * 查询车辆
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryCar/look.action")
	public String queryCar(HttpServletRequest request, String flag) {
		PageBean<Car> pb = new PageBean<>();
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		try {
			//获取分页
			pb = getPageBean(request, user.getFcompanyid(), null);
			//获取当前分页的值
			List<Car> cars = pb.getBeanList();
			//把获取到的数据传回页面
			request.setAttribute("cars", cars);
			request.setAttribute("pb", pb);
			request.setAttribute("flag", flag);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/basicData/carBasicData/carList";
	}

	/**
	 * 跳转到添加页面
	 *
	 * @return
	 */
	@RequestMapping("/insertCar")
	public String insertCar(HttpServletRequest request, String type) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//获取部门
		List<Department> departments = departmentService.queryAdminByController(user.getFcompanyid());
		//获取组织
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		request.setAttribute("department", department);
		request.setAttribute("departments", departments);
		request.setAttribute("type", type);
		return "/backHome/basicData/carBasicData/addCar";
	}

	/**
	 * 添加车辆
	 *
	 * @param request
	 * @param car     属性自动封装
	 * @return 返回车辆查询页面
	 */
	@RequestMapping("/addCar")
	public String addCar(HttpServletRequest request, Car car) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//利用UUID生成fid
		car.setFid(GetFid.UUIDIntoFid());
		//控制单元id
		car.setFcontrolunitid(user.getFcompanyid());
		//创建人id
		car.setFcreatorid(user.getFid());
		//公司id
		car.setCfficompanyid(user.getFcompanyid());
		//获取当前时间
		String createTime = TimeFormat.timeFormat(new Date());
		car.setFcreatetime(createTime);
		//把属性添加进去
		carService.addCar(car);
		//添加日志
		customLogService.addLog("车辆基础资料", createTime + "对车辆进行添加操作", null, user.getFid());
		return "redirect:/DrivingSys/insertCar?type=3";
	}

	/**
	 * 根据fid删除
	 *
	 * @param request  转发到查询页面
	 * @param deleteId 被删除的fid
	 * @return
	 */
	@RequestMapping("/deleteCarByFid")
	public String deleteCarByFid(HttpServletRequest request, String[] deleteId, String fid) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//删除记录
		if ("".equals(fid) || fid == null) {
			for (int i = 0; i < deleteId.length; i++) {
				carService.deleteByPrimaryKey(deleteId[i]);
			}
		} else {
			carService.deleteByPrimaryKey(fid);
		}

		//删除完在调用查询的方法
		queryCar(request, null);
		//添加日志
		customLogService.addLog("车辆基础资料", TimeFormat.timeFormat(new Date()) + "对车辆进行删除操作", null, user.getFid());
		return "/backHome/basicData/carBasicData/carList";
	}

	/**
	 * 根据车牌号码查询
	 *
	 * @param request 转发到查询页面
	 * @param fnumber 传过来的车牌号码
	 * @return 返回查询页面
	 */
	@RequestMapping("/queryCarByFnumber")
	public String queryCarByFnumber(HttpServletRequest request, String fnumber) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		if ("".equals(fnumber)) {
			queryCar(request, null);//为空就调用查询的方法
		} else {
			PageBean<Car> pb = new PageBean<>();
			List<Car> cars = new ArrayList<>();
			fnumber = fnumber.trim();
			try {
				pb = getPageBean(request, user.getFcompanyid(), fnumber);
				cars = pb.getBeanList();
				//把数据传到页面上
				request.setAttribute("pb", pb);
				request.setAttribute("cars", cars);
				request.setAttribute("fnumber", fnumber);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "/backHome/basicData/carBasicData/carList";
	}

	/**
	 * 根据fid查询
	 *
	 * @param request
	 * @param fid     传过来的Fid
	 * @return 跳转到修改页面
	 * @xqid 利用查看详情的
	 */
	@RequestMapping("/selectCarByFid")
	public String selectCarByFid(HttpServletRequest request, String fid, String xqid) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		if ("".equals(xqid) || xqid == null) {
			//把查询到的数据传给页面
			Car car = carService.queryCarByFid(fid);
			//获取部门
			List<Department> departments = departmentService.queryAdminByController(user.getFcompanyid());
			//获取组织
			Department department = departmentService.queryAdminByFid(user.getFcompanyid());
			request.setAttribute("departments", departments);
			request.setAttribute("department", department);
			request.setAttribute("car", car);
			request.setAttribute("xqid", xqid);
		} else {
			//查看详情
			Car car = carService.queryCarByFid(xqid);
			//获取组织
			Department department = departmentService.queryAdminByFid(user.getFcompanyid());
			request.setAttribute("car", car);
			request.setAttribute("xqid", xqid);
			request.setAttribute("department", department);
		}
		return "/backHome/basicData/carBasicData/updateCar";
	}

	/**
	 * 修改车辆信息
	 *
	 * @param request
	 * @param car     属性自动封装
	 * @return 返回查询页面
	 */
	@RequestMapping("/updateCarByFid")
	public String updateCarByFid(HttpServletRequest request, Car car) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//公司id
		car.setCfficompanyid(user.getFcompanyid());
		//控制单元id
		car.setFcontrolunitid(user.getFcompanyid());
		//获取当前修改时间
		String updateTime = TimeFormat.timeFormat(new Date());
		//修改时间
		car.setFlastupdatetime(updateTime);
		//修改人id
		car.setFlastupdateuserid(user.getFid());
		//修改
		carService.modifyCarByFid(car);
		//添加日志
		customLogService.addLog("车辆基础资料", updateTime + "对车辆进行修改操作操作", null, user.getFid());
		return commonController.skipUrl("/queryCar/look.action");
	}

	@RequestMapping("/queCarByFnumber")
	@ResponseBody
	public Boolean queCarByFnumber(HttpServletRequest request, String fnumber) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		String fid = carService.selectCarFnumber(fnumber, user.getFcompanyid());
		if (fid == null) {
			return true;
		} else {
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类
	 * @throws Exception
	 */
	public PageBean<Car> getPageBean(HttpServletRequest request, String companyId, String fnumber) throws Exception {

		int offset;//从第几条数据开始加载
		if (request.getParameter("pager.offset") == null) {
			offset = 0;
		} else {
			offset = Integer.parseInt(request.getParameter("pager.offset"));
		}
		//拼接SQL语句
		StringBuffer psql = new StringBuffer();
		psql.append("select NVL(round(months_between(add_months(sysdate, 3),CFNJDQR),2), -99999) cfnjdqr_type,"); // 小于零则不需要年检标志
		psql.append("NVL(round(months_between(add_months(sysdate, 1),CFJQXDQR),2), -99999) cfjqxdqr_type,"); //小于零则不需要交强险标志
		psql.append("NVL(round(months_between(add_months(sysdate, 1),CFSYXDQR),2), -99999) cfsyxdqr_type,"); //小于零则不需要商业险标志
		psql.append("NVL(round(months_between(add_months(sysdate, 1),CFEJWHRQ),2), -99999) cfejwhrq_type,"); //二级维护维护日期
		psql.append("NVL(round(months_between(add_months(sysdate, 1),CFKMSTXZRQ),2), -99999) cfkmstxzrq_type,"); //科目三通行证
		psql.append("u.name as createName,c.name as updateName,a.fname_l2 as deptName,to_char(t.FCREATETIME,'YYYY-MM-DD HH24:MI:SS') fcreatetime,");
		psql.append("to_char(t.FLASTUPDATETIME,'YYYY-MM-DD HH24:MI:SS') flastupdatetime,to_char(t.CFRHRQ,'YYYY-MM-DD HH24:MI:SS') cfrhrq,");
		psql.append("to_char(t.CFNJDQR,'YYYY-MM-DD HH24:MI:SS') cfnjdqr,to_char(t.CFJQXDQR,'YYYY-MM-DD HH24:MI:SS') cfjqxdqr,");
		psql.append("to_char(t.CFSYXDQR,'YYYY-MM-DD HH24:MI:SS') cfsyxdqr,to_char(t.CFEJWHDQR,'YYYY-MM-DD HH24:MI:SS') cfejwhdqr,");
		psql.append("to_char(t.CFZJDQR,'YYYY-MM-DD HH24:MI:SS') cfzjdqr,to_char(t.CFBYDQR,'YYYY-MM-DD HH24:MI:SS') cfbydqr,");
		psql.append("to_char(t.CFKMSTXZDQR,'YYYY-MM-DD HH24:MI:SS') cfkmstxzdqr,to_char(t.CFSYXRQ,'YYYY-MM-DD HH24:MI:SS') cfsyxrq,");
		psql.append("to_char(t.CFJQXRQ,'YYYY-MM-DD HH24:MI:SS') cfjqxrq,to_char(t.CFNJRQ,'YYYY-MM-DD HH24:MI:SS') cfnjrq,");
		psql.append("to_char(t.CFEJWHRQ,'YYYY-MM-DD HH24:MI:SS') cfejwhrq,to_char(t.CFZJRQ,'YYYY-MM-DD HH24:MI:SS') cfzjrq,");
		psql.append("to_char(t.CFBYRQ,'YYYY-MM-DD HH24:MI:SS') cfbyrq, to_char(t.CFKMSTXZRQ,'YYYY-MM-DD HH24:MI:SS') cfkmstxzrq,");
		psql.append("to_char(t.CFGMRQ,'YYYY-MM-DD HH24:MI:SS') cfgmrq,t.fnumber,t.fsimplename,t.fid,t.cfcjh,t.cffdjh,t.cfcd,");
		psql.append("t.cfpp,t.cfbdh,t.cfgmjg,t.cfllyh,t.FNAME_L2 fnameL2,t.FDESCRIPTION_L2 fdescriptionL2  from ct_ds_car t left join t_e_user u ");
		psql.append("on t.fcreatorid=u.fid  left join t_e_user c on t.flastupdateuserid=c.fid left join ct_ds_admin a on t.cfssjgid=a.fid");
		psql.append(" where t.FCONTROLUNITID= '" + companyId + "' ");
		if (fnumber == null || "".equals(fnumber)) {

		} else {
			psql.append("and t.fnumber like '%" + fnumber + "%'");
		}
		psql.append("order by t.fcreatetime desc");
		int psize = 100; //每页显示数
		int pindex = offset / psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap = carService.selectPage(pindex, psql.toString(), psize);
		PageBean<Car> pb = new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<Car>) paramMap.get("v_cur")); //每页数据集
		return pb;
	}

	/**
	 * 取记录总数 dmz 20160921
	 *
	 * @param psql SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception {

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap = carService.selectPageCount(psql);
		return paramMap;
	}


	/**
	 * 导出Execl
	 *
	 * @param response
	 */
	@RequestMapping("/importCar")
	public void importCarExcel(HttpServletResponse response, HttpServletRequest request, String fnumber) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		List<Object> data = new ArrayList<>();
		List<Car> data_type=new ArrayList<>();
		//查询数据
        List<Car> cars = carService.selectCarExcel(fnumber.trim(), user.getFcompanyid());
        for (int i=0;i<cars.size();i++){
			Car car_type=new Car();
			car_type.setCfjqxdqr_type(cars.get(i).getCfjqxdqr_type());
			car_type.setCfsyxdqr_type(cars.get(i).getCfsyxdqr_type());
			car_type.setCfejwhrq_type(cars.get(i).getCfejwhrq_type());
			car_type.setCfkmstxzrq_type(cars.get(i).getCfkmstxzrq_type());
			data_type.add(car_type);
		}

        for (Car car : cars) {
			data.add(car.getFnumber());//车牌号
			data.add(car.getFnameL2());//车型
//			data.add(car.getFsimplename());//班级简称
//			data.add(car.getFdescriptionL2());//备注
//			data.add(car.getFcreatetime());//创建时间
//			data.add(car.getFlastupdatetime());//最后修改时间
//			data.add(car.getCreateName());//创建人
//			data.add(car.getUpdateName());//修改人
//			data.add(car.getCfrhrq());//入户日期
//			data.add(car.getCfcjh());//车架号
//			data.add(car.getCffdjh());//发动机号
			data.add(car.getCfnjdqr());//年检到期日
			data.add(car.getCfjqxdqr());//交强险到期日-----
			data.add(car.getCfsyxdqr());//商业险到期日----
			data.add(car.getCfejwhdqr());//二级维护到期日
			data.add(car.getCfzjdqr());//综检到期日
			data.add(car.getCfbydqr());//发动机保养到期日
			data.add(car.getCfkmstxzdqr());//科目三通行证到期日
			data.add(car.getDeptName());//所属机构
//			data.add(car.getCfcd());//产地
//			data.add(car.getCfpp());//品牌
//			data.add(car.getCfbdh());//保单号
//			data.add(car.getCfsyxrq());//商业险日期
//			data.add(car.getCfjqxrq());//交强险日期
//			data.add(car.getCfnjrq());//年检日期
//			data.add(car.getCfejwhrq());//二级维护日期-----
//			data.add(car.getCfzjrq());//综检日期
//			data.add(car.getCfbyrq());//发动机保养日期
//			data.add(car.getCfkmstxzrq());//科目三通行证日期------
//			data.add(car.getCfgmjg());//购买价格
//			data.add(car.getCfgmrq());//购买日期
//			data.add(car.getCfllyh());//理论油耗
//			cfjqxdqr_type >= 0||car.cfsyxdqr_type >= 0||car.cfejwhrq_type >= 0||car.cfkmstxzrq_type
		}
		//头部数据
		String head[] = {"车牌号", "车型", "年检到期日", "交强险到期日", "商业险到期日",
				"二级维护到期日", "综检到期日", "发动机保养到期日", "科目三通行证到期日", "所属机构"};
		//长度
		Integer length[] = {5000, 7000, 5000, 5000, 5000,5000, 2600, 2600,5000,5500,3500,5000,5000,5000,5000,5000,
				5000,5000, 4000,3000, 6200, 6200,5000,5000,5000,5000,5000,5000,5000, 3000,5000, 3000};
		try {
			//导出Excel
			CommonExport.importExcelCar(response, "车辆" + TimeFormat.getNowTime2() + ".xls", "车辆", data,data_type, head, length);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
